// 持久化背景页面
// 通过C#隐藏，实现数据持久化
class BackgroundPageService {
    constructor() {
        this.extensionUrl = chrome.runtime.getURL('background/background.html');
    }

    // 打开拓展窗口，等待拓展窗口初始化完成
    async waitforBackgroundOpenAsync(timeoutMs) {
        return new Promise((resolve) => {
            const begin = new Date().getTime();
            const timer = setInterval(async () => {
                const bgTab = await this.getBackgroundTabAsync();
                if (bgTab) {
                    clearInterval(timer);
                    resolve(true);
                }
                const cur = new Date().getTime();
                if (cur - begin >= timeoutMs) {
                    clearInterval(timer);
                    resolve(false);
                }
            }, 100);
        });
    }

    // 打开拓展窗口
    async openBackgroundAsync() {
        try {
            const wnd = await chrome.windows.create({
                state: 'minimized',
                type: 'popup',
                url: this.extensionUrl,
                focused: false,
            });

            console.log('打开background wnd.id:', wnd.id);
            return true;
        } catch (error) {
            console.log('打开background失败');
            return false;
        }
    }

    // 获取background页签
    async getBackgroundTabAsync() {
        const tabs = await chrome.tabs.query({});
        return tabs.find((tab) => tab.url === this.extensionUrl); // windowId
    }
}

let isOpening = false;
const bgService = new BackgroundPageService();

// 打开拓展窗口，如有需要的话
async function openBackgroundNeededAsync() {
    if (isOpening) {
        // 正在打开中
        console.log('[serviceWorker] background正在打开...');
        return;
    }
    isOpening = true;
    await closePopupWnds();
    const bgTab = await bgService.getBackgroundTabAsync();
    if (bgTab) {
        // 已经打开了
        console.log('[serviceWorker] background已经打开');
        isOpening = false;
    } else {
        console.log('[serviceWorker] background开始打开');
        await bgService.openBackgroundAsync();
        // 打开并等待初始化完成
        const success = await bgService.waitforBackgroundOpenAsync(30 * 1000);
        console.log('[serviceWorker] background打开结果:', success);
        isOpening = false;
        reloadTabs();
    }
}

// 关闭无用的页面
async function closePopupWnds() {
    console.log('关闭无用的popup页面');
    const openWnds = await chrome.windows.getAll();
    const pupupWnds = openWnds.filter((win) => win.type === 'popup');
    const openTabs = await chrome.tabs.query({});
    const tabIds = openTabs
        .filter(({ url, windowId }) => {
            return pupupWnds.find((wnd) => wnd.id === windowId) && (!url || (isChromeTabUrl(url) && url.indexOf('html') === -1));
        })
        .map((tab) => tab.id); // 找出所有的popup页面
    if (tabIds.length > 0) {
        await chrome.tabs.remove(tabIds);
    }
}

// 是否为chrome页签
function isChromeTabUrl(url) {
    return url && url.indexOf('chrome://') === 0;
}

// 刷新非chrome页签
function reloadTabs() {
    console.log('刷新tabs');
    try {
        // 刷新页面
        chrome.tabs.query({}, (tabsList) => {
            for (const tab of tabsList) {
                if (!isChromeTabUrl(tab.url)) {
                    chrome.tabs.reload(tab.id, {});
                }
            }
        });
    } catch (e) {
        console.error('reloadTabs error: ' + e);
    }
}

async function onRemoved() {
    if (isOpening) {
        return;
    }
    let openWnds = await chrome.windows.getAll();
    // console.log(openWnds, '当前已打开的窗口');
    openWnds = openWnds.filter((win) => win.type !== 'popup');
    console.log(`[serviceWorker:窗口关闭] 剩余窗口数量: ${openWnds.length}`);
    if (openWnds.length === 0) {
        const bgTab = await bgService.getBackgroundTabAsync();
        if (bgTab) {
            console.log('[serviceWorker::窗口关闭] The background is last open window, closing it now.');
            chrome.windows.remove(bgTab.windowId);
        }
    }
}

// 打开窗口时，判断是否需要打开拓展页面
chrome.windows.onCreated.addListener(openBackgroundNeededAsync);

// 关闭窗口时，如果只剩下了拓展窗口，将拓展窗口关闭
chrome.windows.onRemoved.addListener(onRemoved);

console.log('打开background持久化页面');
openBackgroundNeededAsync();
